<template>
  <div v-if="loading || target">redirecting...</div>
  <div v-else>error</div>
</template>

<script>
import { getConfig } from "@/utils/configAction";
import { addUrlParams } from "@/utils/helper";
import Http from "@/utils/Http";
import { mergeRequestUrl } from "../utils/helper";
import Cookie from "js-cookie";

export default {
  name: "Direction",
  data() {
    return {
      loading: true,
      target: ""
    };
  },
  async mounted() {
    this.loading = false;

    // 检查是否有跳转地址并转码
    let target = decodeURIComponent(getConfig("target") || "");
    this.target = target;

    // 没有跳转地址，停止
    if (!target) return;

    // 获取token
    const token = getConfig("token");

    // 检查token是否有效
    const result = await this.checkToken(token);
    // token无效，删除token，并跳转到登录页
    if (!result) {
      Cookie.remove("token");
      this.$router.replace("/");
      return;
    }

    // 添加token到跳转地址中
    target = addUrlParams(target, { token });

    // 跳转到目标地址
    window.location.href = target;
  },
  methods: {
    /**
     * 检查token是否有效
     */
    async checkToken(token) {
      if (!token) return false;
      try {
        await Http.get(
          mergeRequestUrl("/user/token/validate"),
          {},
          { headers: { token } }
        );
      } catch (err) {
        return false;
      }
      return true;
    }
  }
};
</script>
